package com.speech.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.ontbee.legacyforks.cn.pedant.SweetAlert.SweetAlertDialog;
import com.speech.MyApplication;
import com.speech.R;
import com.speech.adapter.HomeFragmentAdapter;
import com.speech.constant.PrefsConstant;
import com.speech.db.SharedPreferenceHelper;
import com.speech.entity.BaseEntity;
import com.speech.fragment.HomeFragment;
import com.speech.fragment.MineFragment;
import com.speech.fragment.MissionFragment;
import com.speech.http.BaseCallback;
import com.speech.net.BasicCallBack;
//import com.speech.net.HttpCommunicationManager;
import com.speech.net.constant.EnumReqestActionCode;
import com.speech.net.entity.MessageC2S;
import com.speech.net.entity.MessageC2SBuilder;
import com.speech.net.entity.MessageS2C;
import com.speech.net.result.UpdateInfo_Result;
import com.speech.result.Result;
import com.speech.utils.ApkVersionUtil;
import com.speech.utils.DeviceUtil;
import com.speech.utils.JsonProcessor;

import java.util.ArrayList;
import java.util.List;

import me.leolin.shortcutbadger.ShortcutBadger;
import retrofit2.Call;

public class HomeActivity extends BaseActivity implements View.OnClickListener {

    private ViewPager vp;

    private ConstraintLayout cl_home;
    private ConstraintLayout cl_mission;
    private ConstraintLayout cl_mine;

    private ImageView img_home;
    private ImageView img_mission;
    private ImageView img_mine;

    private TextView tv_home;
    private TextView tv_mission;
    private TextView tv_mine;

    private SweetAlertDialog dialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);



        _initView();

        vp.setOffscreenPageLimit(3);

        vp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                _changeTabView(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });

        cl_home.setOnClickListener(this);
        cl_mission.setOnClickListener(this);
        cl_mine.setOnClickListener(this);


        //在这里进行检查版本升级
//        _temp_check_version_change();//TODO:临时的强制升级
//        _check_version_change();

    }

    private void _temp_check_version_change() {

        //TODO: 接口请求 版本更新
//        MessageC2S msg_c2s = MessageC2SBuilder.buildGeneral_MessageC2S(this, EnumReqestActionCode.查询更新, null);
//        String json = JsonProcessor.StcGetJson(msg_c2s);
//        HttpCommunicationManager.getInstance().doPost(json, new BasicCallBack(HomeActivity.this, json, new BasicCallBack.BasicCallBackListener() {
//            @Override
//            public void success(MessageS2C msg_s2c) {
//                UpdateInfo_Result updateInfo_result = JsonProcessor.StcGetObject(UpdateInfo_Result.class, msg_s2c.strData);
//
//                if (updateInfo_result != null && _check_need_update(updateInfo_result)) {
//                    SweetAlertDialog dialog = new SweetAlertDialog(HomeActivity.this, SweetAlertDialog.WARNING_TYPE)
//                            .setTitleText("新版本上线啦")
//                            .setContentText("请进入公众号内下载最新版本")
//                            .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
//                                @Override
//                                public void onClick(SweetAlertDialog sweetAlertDialog) {
//                                    sweetAlertDialog.dismiss();
//                                    MyApplication.getInstance().destory();
//                                    HomeActivity.this.finish();
//                                }
//                            });
//                    dialog.setCancelable(false);
//                    dialog.show();
//                }
//
//            }
//
//            @Override
//            public void fail(MessageS2C msg_s2c) {
//
//            }
//        }));


        String uid,token;
        SharedPreferenceHelper spf = new SharedPreferenceHelper(this, PrefsConstant.FILE_USER_INFO);
        String lUID = (String) spf.getData(PrefsConstant.KEY_USER_INFO_LONG_UID, "");
        uid = lUID;
        String lToken = (String) spf.getData(PrefsConstant.KEY_USER_INFO_LONG_TOKEN, "");
        token = lToken;
        Call<Result<BaseEntity>> call = MyApplication.getInstance().getApiService()
                .upApp(uid, DeviceUtil.getDeviceID(this)
                        ,token,ApkVersionUtil.getVersionName(this));
        call.enqueue(new BaseCallback<BaseEntity>() {
            @Override
            public void onSuccess(BaseEntity baseEntity) {
//                dialog = new SweetAlertDialog(HomeActivity.this, SweetAlertDialog.WARNING_TYPE)
//                        .setTitleText("新版本上线啦")
//                        .setContentText("请进入公众号内下载最新版本")
//                        .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
//                            @Override
//                            public void onClick(SweetAlertDialog sweetAlertDialog) {
//                                sweetAlertDialog.dismiss();
//                                MyApplication.getInstance().destory();
//                                HomeActivity.this.finish();
//                            }
//                        });
//                dialog.setCancelable(false);
//                dialog.show();
            }

            @Override
            public void onAbnormal(String msg) {

            }

            @Override
            public void onFailure(String msg) {

            }
        });
    }

    private void _check_version_change() {

        //TODO: 接口请求
//        MessageC2S msg_c2s = MessageC2SBuilder.buildGeneral_MessageC2S(this, EnumReqestActionCode.查询更新, null);
//        String json = JsonProcessor.StcGetJson(msg_c2s);
//        HttpCommunicationManager.getInstance().doPost(json, new BasicCallBack(HomeActivity.this, json, new BasicCallBack.BasicCallBackListener() {
//            @Override
//            public void success(MessageS2C msg_s2c) {
//                UpdateInfo_Result updateInfo_result = JsonProcessor.StcGetObject(UpdateInfo_Result.class, msg_s2c.strData);
//
//                if (_check_need_update(updateInfo_result)) {
////                    updateInfo_result.strUpdateURL
//                }
//
//            }
//
//            @Override
//            public void fail(MessageS2C msg_s2c) {
//
//            }
//        }));
    }

    private boolean _check_need_update(UpdateInfo_Result updateInfo_result) {

        String[] strServerVersion = updateInfo_result.strEnforcementUpdateVersion.split("\\.");
        String[] strCurrentVersion = ApkVersionUtil.getVersionName(HomeActivity.this).split("\\.");
        boolean bNeedUpdate = false;

        for (int index = 0; index < strServerVersion.length; index++) {
            int iServerVerison = Integer.valueOf(strServerVersion[index]);
            int iCurrentVersion = Integer.valueOf(strCurrentVersion[index]);
            if (iServerVerison > iCurrentVersion) {
                bNeedUpdate = true;
                break;
            }
        }

        return bNeedUpdate;
    }


    private void _changeTabView(int position) {
        switch (position) {
            case 0:
                vp.setCurrentItem(position);
                img_home.setImageResource(R.drawable.activity_home_home_black_1x);
                img_mine.setImageResource(R.drawable.activity_home_mine_gray_1x);
                img_mission.setImageResource(R.drawable.activity_home_mission_gray_1x);

                tv_home.setTextColor(Color.BLACK);
                tv_mission.setTextColor(getResources().getColor(R.color.colorGray_DefaultState));
                tv_mine.setTextColor(getResources().getColor(R.color.colorGray_DefaultState));

                break;
            case 1:
                vp.setCurrentItem(position);
                img_home.setImageResource(R.drawable.activity_home_home_gray_1x);
                img_mission.setImageResource(R.drawable.activity_home_mission_black_1x);
                img_mine.setImageResource(R.drawable.activity_home_mine_gray_1x);

                tv_home.setTextColor(getResources().getColor(R.color.colorGray_DefaultState));
                tv_mission.setTextColor(Color.BLACK);
                tv_mine.setTextColor(getResources().getColor(R.color.colorGray_DefaultState));

                break;
            case 2:
                vp.setCurrentItem(position);
                img_home.setImageResource(R.drawable.activity_home_home_gray_1x);
                img_mission.setImageResource(R.drawable.activity_home_mission_gray_1x);
                img_mine.setImageResource(R.drawable.activity_home_mine_black_1x);

                tv_home.setTextColor(getResources().getColor(R.color.colorGray_DefaultState));
                tv_mission.setTextColor(getResources().getColor(R.color.colorGray_DefaultState));
                tv_mine.setTextColor(Color.BLACK);

                break;
        }
    }

    private void _initView() {
        vp = findViewById(R.id.vp_home);

        cl_home = findViewById(R.id.cl_home_tab_home);
        cl_mission = findViewById(R.id.cl_home_tab_mission);
        cl_mine = findViewById(R.id.cl_home_tab_mine);

        img_home = findViewById(R.id.img_home_tab_home);
        img_mission = findViewById(R.id.img_home_tab_mission);
        img_mine = findViewById(R.id.img_home_tab_mine);

        tv_home = findViewById(R.id.tv_home_tab_home);
        tv_mission = findViewById(R.id.tv_home_tab_mission);
        tv_mine = findViewById(R.id.tv_home_tab_mine);

        // 初始选中首页项
        _changeTabView(0);

        // 加载fragment
        List<Fragment> lstFragment = new ArrayList<>();
        lstFragment.add(new HomeFragment());
        lstFragment.add(new MissionFragment());
        lstFragment.add(new MineFragment());
        HomeFragmentAdapter adapter = new HomeFragmentAdapter(getSupportFragmentManager(), lstFragment);
        vp.setAdapter(adapter);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.cl_home_tab_home:
                _changeTabView(0);
                break;
            case R.id.cl_home_tab_mission:
                _changeTabView(1);
                break;
            case R.id.cl_home_tab_mine:
                _changeTabView(2);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dialog != null){
            dialog.dismissWithAnimation();
        }
    }
}
